import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @program: JavaWeb
 * @description 案例
 * @author: taoli
 * @create: 2020-12-11 14:24
 **/
@WebServlet("/captche.png")
public class demo extends HttpServlet {
    @Override  //resp给客户的  rep给服务器
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletOutputStream sos=resp.getOutputStream();//输出数据通道
        ImageIO.write(generatePic(100,40),"JPEG",sos);//借助ImaheIO类 生成一张格式为JPEG的图片
        sos.flush();//解决缓冲区的数据
        sos.close();//关掉输出流
    }
    private BufferedImage generatePic(int width , int height){
        BufferedImage image = new BufferedImage(100,40,BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(Color.white);//设置图片颜色
        g.fillRect(0,0,width,height);//填充矩形框
        g.setFont(new Font("宋体",Font.PLAIN,45)); //字体大小 (宋体，粗细，大小)
        Random rnd = new Random();//定义生成随机数
        Color color = new Color(rnd.nextInt(256),rnd.nextInt(256),rnd.nextInt(256));//随机生成RGB255
        g.setColor(color);//得到定义随机颜色

        String str ="";
        for(int a = 0;a<4;a++){
            str = String.valueOf(rnd.nextInt(10));//输出随机数字
            g.setColor(new Color(rnd.nextInt(255),rnd.nextInt(255),rnd.nextInt(255)));//设置字体颜色
            g.drawString(str,25*a,35);
        }//随机生成数字方法

        for(int i=0;i<10;i++){
            g.drawLine(rnd.nextInt(width),rnd.nextInt(height),rnd.nextInt(width),rnd.nextInt(height));
        }//随机的干扰线条

        for(int i=0;i<15;i++){
            int x = rnd.nextInt(width);
            int y = rnd.nextInt(height);
            g.drawOval(x,y,3,3);
        }//画随机的圆圈噪点
        return image;//输出图片
    }
}

